<template>
	<view class="rel_wrap">
		<!-- <view class="title">逝者信息</view> -->
		<comp-navbar title="逝者信息" bgColor="transparent" :fixed="false" @back="handleback" :custom="true"></comp-navbar>
		<up-form ref="form" :model="formstate" :rules="rules" :labelWidth="90">
			<up-form-item label="逝者照片" prop="avatar">
				<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="avatar" :maxCount="1"
					:previewFullImage="false"></up-upload>
			</up-form-item>
			<up-form-item label="逝者姓名" prop="name">
				<up-input v-model="formstate.name" placeholder="请填写逝者姓名"></up-input>
			</up-form-item>
			<up-form-item label="逝者性别" prop="sex">
				<up-radio-group v-model="formstate.sex" placement="row" @change="groupChange">
					<!-- <up-radio activeColor="#626ac3" label="男"></up-radio>
					<up-radio activeColor="#626ac3" label="女"></up-radio> -->
					<up-radio :customStyle="{marginRight: '8px'}" v-for="(item, index) in radiolist" :key="index"
						:label="item.name" :name="item.name">
					</up-radio>
				</up-radio-group>
			</up-form-item>
			<up-button class="savebtn" @click="handlesave" text="保存"></up-button>
		</up-form>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
		unref,
		watch
	} from 'vue';
	import {
		request,
		baseUrl,
		apiUrl
	} from '@/utils/request.js'

	const props = defineProps({
		config: {
			type: Object
		},
		data: {
			type: Object
		}
	})






	const form = ref(null);
	const formstate = ref({
		name: '',
		avatar: '',
		sex: ''
	})
	const rules = {
		name: [{
			required: true,
			message: '请填写逝者姓名',
			trigger: ['blur', 'change'],
		}],
		sex: [{
			required: true,
			message: '请选择逝者性别',
			trigger: ['blur', 'change'],
		}],
	}

	const fileList = ref([])

	const flag = ref(false)
	const editalone = ref({})

	watch(() => props.config.editAlone, (newval) => {
		console.log('newval', newval)
		const len = Object.keys(newval.value)
		if (len.length) {
			editalone.value = {
				...newval.value
			}
			//const editalone = unref(editalone.value)
			//console.log('editalone--', props.config.editAlone, editalone)
			formstate.value.name = editalone.value.name || editalone.value.Name
			formstate.value.sex = editalone.value.sexname;
			formstate.value.avatar = editalone.value?.ImgUrl || editalone.value?.imgUrl

			fileList.value = [{
				url: `${baseUrl}/${editalone.value?.ImgUrl || editalone.value.imgUrl}`
			}]
			flag.value = true

		} else {
			fileList.value = []
			flag.value = false
		}
	}, {
		deep: true,
		immediate: true
	})

	onMounted(() => {
		// const editalone = uni.getStorageSync('editalone')
		// if (editalone) {
		// 	// 编辑初始化
		// 	formstate.value.name = editalone.name || editalone.Name
		// 	formstate.value.sex = editalone.sexname;
		// 	formstate.value.avatar = editalone?.ImgUrl || editalone.imgUrl

		// 	fileList.value = [{
		// 		url: `${baseUrl}/${editalone?.ImgUrl || editalone.imgUrl}`
		// 	}]
		// 	console.log('fileList', fileList)
		// } else {
		// 	fileList.value = []
		// }
	})

	const handleback = () => {
		console.log('sss')
		props.config.relClose && props.config.relClose()
	}

	// 头像 url: https://cdn.uviewui.com/uview/swiper/1.jpg



	// 删除图片
	const deletePic = (event) => {
		fileList.value.splice(event.index, 1);
	};

	// 上传图片
	const uploadFilePromise = async (url, res) => {
		//console.log(url, res)

		return new Promise((resolve, reject) => {
			let result = uni.uploadFile({
				url: apiUrl + '/SZ_FuneralCompanyTheDeceased/UploadV1', // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'fileInput',
				success: (res) => {
					console.log('res', JSON.parse(res.data))
					const data = JSON.parse(res.data)
					formstate.value.avatar = data?.Value?.Data
					resolve(data?.Value?.Data);

				},
			});
		});
	}

	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList.value.length;
		lists.map((item) => {
			fileList.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url, lists[i]);
			let item = fileList.value[fileListLen];
			fileList.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};

	// 性别
	const radiolist = ref([{
			name: '男',
			key: 0
		},
		{
			name: '女',
			key: 1
		},
	])

	const groupChange = (n) => {
		console.log('groupChange', n);
	};

	//提交

	const handlesave = (e) => {

		form.value.validate()?.then(async res => {
			if (res) {
				//uni.$u.toast('校验通过')
				//console.log('formstate', formstate)
				const data = {
					name: formstate.value.name,
					sex: formstate.value.sex == '男' ? 0 : 1, // == '男' ? 0 : 1
					sexname: formstate.value.sex,
					imgUrl: formstate.value.avatar,
				}
				// const res = await request({
				// 	url: '/SZ_FuneralCompanyTheDeceased/AddFuneralCompanyTheDeceased',
				// 	data,
				// })
				const funeralinfo = uni.getStorageSync('funeralinfo') || [];
				//const editalone = uni.getStorageSync('editalone')
				if (!flag.value) {
					//data.ID = Date.now()
					funeralinfo.push(data)
					uni.$u.toast('逝者新增成功')
				} else {

					funeralinfo.forEach(v => {
						if (v.ID == editalone.value.ID) {
							v.name = data.name
							v.sex = data.sex
							v.sexname = data.sexname
							v.imgUrl = data.imgUrl
						}
					})
					console.log('编辑', editalone, funeralinfo, data)
					uni.$u.toast('逝者编辑成功')
				}
				uni.setStorageSync('funeralinfo', funeralinfo)
				console.log('props.config.getAllszInfo', props.config)
				props.config.getAllszInfo && props.config.getAllszInfo()
				props.config.relClose && props.config.relClose()
			} else {
				// uni.$u.toast('校验失败')
				console.log('逝者校验失败')
			}
		}).catch(errors => {
			console.log(errors)
			console.log('逝者校验失败', errors)
		})
	}
</script>

<style lang="scss" scoped>
	.rel_wrap {
		width: 90vw;
		margin: 0 auto;
		padding: 20rpx;
		background-color: #fff;
		box-sizing: border-box;

		.title {
			padding: 20rpx 0;
			text-align: center;
		}

		.savebtn {
			width: 90%;
			height: 80rpx;
			margin: 40rpx auto;
			line-height: 80rpx;
			font-size: 28rpx;
			text-align: center;
			color: #fff;
			background-color: $act-color;
			border-radius: 40rpx;
		}
	}
</style>